//! Socket

use crate::consts::*;
use crate::datagram::Datagram;
use crate::sender;
use crate::Addr;
use core::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use fixed_queue::LinearMap;
use futures_intrusive::buffer::ArrayBuf;
use futures_intrusive::channel::shared::*;
use spin::Mutex;
type BTreeMap<K, V> = LinearMap<K, V, LISTENERS_LEN>;

static CH_LIST: Mutex<BTreeMap<u8, WaitDataSender>> = Mutex::new(BTreeMap::new());

pub struct Respose {
    pub body: VecBody,
    pub remote: Addr,
}
type RingBody = ArrayBuf<Respose, [Respose; 1]>;
type WaitDataSender = GenericSender<Mutex<()>, Respose, RingBody>;
type WaitDataRecver = GenericReceiver<Mutex<()>, Respose, RingBody>;

struct Timeout {
    time: AtomicU64,
    num: AtomicU8,
}
impl Timeout {
    pub fn new(timeout: u64) -> Timeout {
        Timeout {
            time: AtomicU64::new(timeout),
            num: AtomicU8::new(1),
        }
    }
    pub fn get(&self) -> u64 {
        self.time.load(Ordering::Relaxed)
    }
    pub fn update(&self, consum: u64) {
        let _err = self
            .num
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |num| {
                if num < 200 {
                    let _err =
                        self.time
                            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |time| {
                                Some((time * num as u64 + 2 * (consum + 100)) / (num as u64 + 1))
                            });
                    Some(num + 1)
                } else {
                    None
                }
            });
    }
}

pub struct Config {
    pub retry: u8,
}
pub struct Socket {
    port: u8,
    remote: Option<Addr>,
    recver: WaitDataRecver,
    timeout: Timeout,
    cfg: Config,
}
impl Socket {
    /// 创建socket
    pub fn new(port: u8, config: Config) -> Result<Socket, &'static str> {
        let mut ch_list = CH_LIST.lock();
        if let Some(_) = ch_list.get(&port) {
            return Err("repeat.");
        }
        let (sender, recver) = generic_channel(1);
        if ch_list.len() >= LISTENERS_LEN {
            return Err("full.");
        }
        ch_list.insert(port, sender);

        Ok(Socket {
            port: port,
            remote: None,
            recver: recver,
            timeout: Timeout::new(10_000),
            cfg: config,
        })
    }
    /// 设置绑定设备
    pub fn bind(&mut self, remote: Addr) {
        self.remote = Some(remote)
    }
    /// 发送数据给绑定设备
    pub async fn send(&self, data: &[u8]) -> Result<(), ()> {
        if let Some(remote) = &self.remote {
            if let Ok(consum) =
                sender::send(self.port, remote, data, self.cfg.retry, self.timeout.get()).await
            {
                self.timeout.update(consum);
                return Ok(());
            }
        }
        return Err(());
    }
    /// 发送数据给目标设备
    pub async fn send_to(&self, data: &[u8], remote: &Addr) -> Result<(), ()> {
        if let Ok(consum) =
            sender::send(self.port, remote, data, self.cfg.retry, self.timeout.get()).await
        {
            self.timeout.update(consum);
            return Ok(());
        }
        return Err(());
    }
    /// 接收数据
    pub async fn recv(&self) -> Result<Respose, ()> {
        if let Some(rep) = self.recver.receive().await {
            Ok(rep)
        } else {
            Err(())
        }
    }
}

pub(crate) fn when_recv(datagram: &Datagram, remote: Addr) {
    let ch_list = CH_LIST.lock();
    if let Some(sender) = ch_list.get(&datagram.head().dstport()) {
        let rep = Respose {
            body: VecBody::from(datagram.body()),
            remote: remote,
        };
        task_stream::spawn(sender.send(rep));
    }
}
